//
//  WaterfallController.swift
//  HHSwift
//
//  Created by 华宏 on 2020/1/29.
//  Copyright © 2020 huahong. All rights reserved.
//

import UIKit

class WaterfallController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "瀑布流"

        self.view.addSubview(self.collectionView)
    }
    

    lazy var collectionView: UICollectionView = {
        let layout = WaterFallLayout.init()
        layout.minimumInteritemSpacing = 5
        layout.minimumLineSpacing = 5
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        layout.columnCount = 3
        layout.delegate = self

//        let columnCount = 3
//        let space = CGFloat(columnCount - 1) * layout.minimumInteritemSpacing
//        let itemWidth = (self.view.bounds.size.width - layout.sectionInset.left - layout.sectionInset.right - space) / CGFloat(columnCount)
//        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)



        let collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.alwaysBounceVertical = true
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        collectionView.keyboardDismissMode = .onDrag
        return collectionView
    }()

}

extension WaterfallController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,WaterFallLayoutDelegate {

    //MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 33
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        cell.contentView.backgroundColor = UIColor.randomColor()

        return cell
    }

    //MARK: - WaterfallLayoutDelegate
    func waterFallLayout(layout:WaterFallLayout,heightFor indexPath:IndexPath,itemWidth:CGFloat) -> CGFloat {

        let randomWidth = CGFloat(arc4random() % 100 + 200)
        let randomHeight = CGFloat(arc4random() % 100 + 200)
        return itemWidth * randomHeight / randomWidth

    }
}
